/**
 * 运行时配置
 */
import { history } from 'umi';
/* 1. patchRoutes({ routes }) */
interface IRoute {
  component?: string;
  exact?: boolean;
  path?: string;
  routes?: IRoute[];
  wrappers?: string[];
  title?: string;
  __toMerge?: boolean;
  __isDynamic?: boolean;
  [key: string]: any;
}
interface IPatchRoutesParams {
  routes: IRoute[];
}
export function patchRoutes({ routes }: IPatchRoutesParams) {
  routes.unshift({
    path: '/test',
    exact: true,
    component: require('@/extraRoutes/Test/index').default,
  });
}

/* 2. render 配置配合使用，请求服务端根据响应动态更新路由， */
// let extraRoutes: IRoute[] = [];
// export function patchRoutes({ routes }: IPatchRoutesParams) {
//   return [...routes, ...extraRoutes];
// }
// export function render() {
//   fetch('/api/routes').then((res) => { extraRoutes = res.routes })
// }

/* 3. render(oldRender: Function) */
export function render(oldRender: any) {
  console.log('-------render-------------------');

  oldRender();
  // fetch('/api/auth').then(auth => {
  //   if (auth.isLogin) {
  //     oldRender();
  //   } else {
  //     history.redirectTo('/login');
  //   }
  // });
}

/* 4. onRouteChange({ routes, matchedRoutes, location, action }) */
export function onRouteChange({
  location,
  routes,
  action,
  matchedRoutes,
}: any) {
  // 埋点统计
  // bacon(location.pathname);
  console.log('------------route change');

  console.log(matchedRoutes);
  // 设置标题
  if (matchedRoutes.length) {
    document.title =
      matchedRoutes[matchedRoutes.length - 1].route.title || '默认标题';
  }
}

/* 5. rootContainer(LastRootContainer, args) */
// 修改交给 react-dom 渲染时的根组件。 比如用于在外面包一个 Provider，
// export function rootContainer(container) {
//   return React.createElement(ThemeProvider, null, container);
// }
